

<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="Description" content="scikit-learn: machine learning in Python">

  
  <title>6.3. Preprocessing data &mdash; scikit-learn 0.22 documentation</title>
  
  <link rel="canonical" href="http://scikit-learn.org/stable/modules/preprocessing.html" />

  
  <link rel="shortcut icon" href="../_static/favicon.ico"/>
  

  <link rel="stylesheet" href="../_static/css/vendor/bootstrap.min.css" type="text/css" />
  <link rel="stylesheet" href="../_static/gallery.css" type="text/css" />
  <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script> 
</head>
<body>
<nav id="navbar" class="sk-docs-navbar navbar navbar-expand-md navbar-light bg-light py-0">
  <div class="container-fluid sk-docs-container px-0">
      <a class="navbar-brand py-0" href="../index.html">
        <img
          class="sk-brand-img"
          src="../_static/scikit-learn-logo-small.png"
          alt="logo"/>
      </a>
    <button
      id="sk-navbar-toggler"
      class="navbar-toggler"
      type="button"
      data-toggle="collapse"
      data-target="#navbarSupportedContent"
      aria-controls="navbarSupportedContent"
      aria-expanded="false"
      aria-label="Toggle navigation"
    >
      <span class="navbar-toggler-icon"></span>
    </button>

    <div class="sk-navbar-collapse collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item">
          <a class="sk-nav-link nav-link" href="../install.html">Install</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link" href="../user_guide.html">User Guide</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link" href="classes.html">API</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link" href="../auto_examples/index.html">Examples</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../getting_started.html">Getting Started</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../tutorial/index.html">Tutorial</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../glossary.html">Glossary</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../developers/index.html">Development</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../faq.html">FAQ</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../related_projects.html">Related packages</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../roadmap.html">Roadmap</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="../about.html">About us</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="https://github.com/scikit-learn/scikit-learn">GitHub</a>
        </li>
        <li class="nav-item">
          <a class="sk-nav-link nav-link nav-more-item-mobile-items" href="https://scikit-learn.org/dev/versions.html">Other Versions</a>
        </li>
        <li class="nav-item dropdown nav-more-item-dropdown">
          <a class="sk-nav-link nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">More</a>
          <div class="dropdown-menu" aria-labelledby="navbarDropdown">
              <a class="sk-nav-dropdown-item dropdown-item" href="../getting_started.html">Getting Started</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../tutorial/index.html">Tutorial</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../glossary.html">Glossary</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../developers/index.html">Development</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../faq.html">FAQ</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../related_projects.html">Related packages</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../roadmap.html">Roadmap</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="../about.html">About us</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="https://github.com/scikit-learn/scikit-learn">GitHub</a>
              <a class="sk-nav-dropdown-item dropdown-item" href="https://scikit-learn.org/dev/versions.html">Other Versions</a>
          </div>
        </li>
      </ul>
      <div id="searchbox" role="search">
          <div class="searchformwrapper">
          <form class="search" action="../search.html" method="get">
            <input class="sk-search-text-input" type="text" name="q" aria-labelledby="searchlabel" />
            <input class="sk-search-text-btn" type="submit" value="Go" />
          </form>
          </div>
      </div>
    </div>
  </div>
</nav>
<div class="d-flex" id="sk-doc-wrapper">
    <input type="checkbox" name="sk-toggle-checkbox" id="sk-toggle-checkbox">
    <label id="sk-sidemenu-toggle" class="sk-btn-toggle-toc btn sk-btn-primary" for="sk-toggle-checkbox">Toggle Menu</label>
    <div id="sk-sidebar-wrapper" class="border-right">
      <div class="sk-sidebar-toc-wrapper">
        <div class="sk-sidebar-toc-logo">
          <a href="../index.html">
            <img
              class="sk-brand-img"
              src="../_static/scikit-learn-logo-small.png"
              alt="logo"/>
          </a>
        </div>
        <div class="btn-group w-100 mb-2" role="group" aria-label="rellinks">
            <a href="feature_extraction.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="6.2. Feature extraction">Prev</a><a href="../data_transforms.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="6. Dataset transformations">Up</a>
            <a href="impute.html" role="button" class="btn sk-btn-rellink py-1" sk-rellink-tooltip="6.4. Imputation of missing values">Next</a>
        </div>
        <div class="alert alert-danger p-1 mb-2" role="alert">
          <p class="text-center mb-0">
          <strong>scikit-learn 0.22</strong><br/>
          <a href="http://scikit-learn.org/dev/versions.html">Other versions</a>
          </p>
        </div>
        <div class="alert alert-warning p-1 mb-2" role="alert">
          <p class="text-center mb-0">
            Please <a class="font-weight-bold" href="../about.html#citing-scikit-learn"><string>cite us</string></a> if you use the software.
          </p>
        </div>
          <div class="sk-sidebar-toc">
            <ul>
<li><a class="reference internal" href="#">6.3. Preprocessing data</a><ul>
<li><a class="reference internal" href="#standardization-or-mean-removal-and-variance-scaling">6.3.1. Standardization, or mean removal and variance scaling</a><ul>
<li><a class="reference internal" href="#scaling-features-to-a-range">6.3.1.1. Scaling features to a range</a></li>
<li><a class="reference internal" href="#scaling-sparse-data">6.3.1.2. Scaling sparse data</a></li>
<li><a class="reference internal" href="#scaling-data-with-outliers">6.3.1.3. Scaling data with outliers</a></li>
<li><a class="reference internal" href="#centering-kernel-matrices">6.3.1.4. Centering kernel matrices</a></li>
</ul>
</li>
<li><a class="reference internal" href="#non-linear-transformation">6.3.2. Non-linear transformation</a><ul>
<li><a class="reference internal" href="#mapping-to-a-uniform-distribution">6.3.2.1. Mapping to a Uniform distribution</a></li>
<li><a class="reference internal" href="#mapping-to-a-gaussian-distribution">6.3.2.2. Mapping to a Gaussian distribution</a></li>
</ul>
</li>
<li><a class="reference internal" href="#normalization">6.3.3. Normalization</a></li>
<li><a class="reference internal" href="#encoding-categorical-features">6.3.4. Encoding categorical features</a></li>
<li><a class="reference internal" href="#discretization">6.3.5. Discretization</a><ul>
<li><a class="reference internal" href="#k-bins-discretization">6.3.5.1. K-bins discretization</a></li>
<li><a class="reference internal" href="#feature-binarization">6.3.5.2. Feature binarization</a></li>
</ul>
</li>
<li><a class="reference internal" href="#imputation-of-missing-values">6.3.6. Imputation of missing values</a></li>
<li><a class="reference internal" href="#generating-polynomial-features">6.3.7. Generating polynomial features</a></li>
<li><a class="reference internal" href="#custom-transformers">6.3.8. Custom transformers</a></li>
</ul>
</li>
</ul>

          </div>
      </div>
    </div>
    <div id="sk-page-content-wrapper">
      <div class="sk-page-content container-fluid body px-md-3" role="main">
        
  <div class="section" id="preprocessing-data">
<span id="preprocessing"></span><h1>6.3. Preprocessing data<a class="headerlink" href="#preprocessing-data" title="Permalink to this headline">¶</a></h1>
<p>The <code class="docutils literal notranslate"><span class="pre">sklearn.preprocessing</span></code> package provides several common
utility functions and transformer classes to change raw feature vectors
into a representation that is more suitable for the downstream estimators.</p>
<p>In general, learning algorithms benefit from standardization of the data set. If
some outliers are present in the set, robust scalers or transformers are more
appropriate. The behaviors of the different scalers, transformers, and
normalizers on a dataset containing marginal outliers is highlighted in
<a class="reference internal" href="../auto_examples/preprocessing/plot_all_scaling.html#sphx-glr-auto-examples-preprocessing-plot-all-scaling-py"><span class="std std-ref">Compare the effect of different scalers on data with outliers</span></a>.</p>
<div class="section" id="standardization-or-mean-removal-and-variance-scaling">
<span id="preprocessing-scaler"></span><h2>6.3.1. Standardization, or mean removal and variance scaling<a class="headerlink" href="#standardization-or-mean-removal-and-variance-scaling" title="Permalink to this headline">¶</a></h2>
<p><strong>Standardization</strong> of datasets is a <strong>common requirement for many
machine learning estimators</strong> implemented in scikit-learn; they might behave
badly if the individual features do not more or less look like standard
normally distributed data: Gaussian with <strong>zero mean and unit variance</strong>.</p>
<p>In practice we often ignore the shape of the distribution and just
transform the data to center it by removing the mean value of each
feature, then scale it by dividing non-constant features by their
standard deviation.</p>
<p>For instance, many elements used in the objective function of
a learning algorithm (such as the RBF kernel of Support Vector
Machines or the l1 and l2 regularizers of linear models) assume that
all features are centered around zero and have variance in the same
order. If a feature has a variance that is orders of magnitude larger
than others, it might dominate the objective function and make the
estimator unable to learn from other features correctly as expected.</p>
<p>The function <a class="reference internal" href="generated/sklearn.preprocessing.scale.html#sklearn.preprocessing.scale" title="sklearn.preprocessing.scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">scale</span></code></a> provides a quick and easy way to perform this
operation on a single array-like dataset:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn</span> <span class="kn">import</span> <span class="n">preprocessing</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_train</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span> <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">2.</span><span class="p">],</span>
<span class="gp">... </span>                    <span class="p">[</span> <span class="mf">2.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">],</span>
<span class="gp">... </span>                    <span class="p">[</span> <span class="mf">0.</span><span class="p">,</span>  <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_scaled</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">scale</span><span class="p">(</span><span class="n">X_train</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">X_scaled</span>
<span class="go">array([[ 0.  ..., -1.22...,  1.33...],</span>
<span class="go">       [ 1.22...,  0.  ..., -0.26...],</span>
<span class="go">       [-1.22...,  1.22..., -1.06...]])</span>
</pre></div>
</div>
<p>Scaled data has zero mean and unit variance:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X_scaled</span><span class="o">.</span><span class="n">mean</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="go">array([0., 0., 0.])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">X_scaled</span><span class="o">.</span><span class="n">std</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="go">array([1., 1., 1.])</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">preprocessing</span></code> module further provides a utility class
<a class="reference internal" href="generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler" title="sklearn.preprocessing.StandardScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StandardScaler</span></code></a> that implements the <code class="docutils literal notranslate"><span class="pre">Transformer</span></code> API to compute
the mean and standard deviation on a training set so as to be
able to later reapply the same transformation on the testing set.
This class is hence suitable for use in the early steps of a
<a class="reference internal" href="generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline" title="sklearn.pipeline.Pipeline"><code class="xref py py-class docutils literal notranslate"><span class="pre">sklearn.pipeline.Pipeline</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">scaler</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">StandardScaler</span><span class="p">()</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scaler</span>
<span class="go">StandardScaler()</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">scaler</span><span class="o">.</span><span class="n">mean_</span>
<span class="go">array([1. ..., 0. ..., 0.33...])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">scaler</span><span class="o">.</span><span class="n">scale_</span>
<span class="go">array([0.81..., 0.81..., 1.24...])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">scaler</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X_train</span><span class="p">)</span>
<span class="go">array([[ 0.  ..., -1.22...,  1.33...],</span>
<span class="go">       [ 1.22...,  0.  ..., -0.26...],</span>
<span class="go">       [-1.22...,  1.22..., -1.06...]])</span>
</pre></div>
</div>
<p>The scaler instance can then be used on new data to transform it the
same way it did on the training set:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X_test</span> <span class="o">=</span> <span class="p">[[</span><span class="o">-</span><span class="mf">1.</span><span class="p">,</span> <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">scaler</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
<span class="go">array([[-2.44...,  1.22..., -0.26...]])</span>
</pre></div>
</div>
<p>It is possible to disable either centering or scaling by either
passing <code class="docutils literal notranslate"><span class="pre">with_mean=False</span></code> or <code class="docutils literal notranslate"><span class="pre">with_std=False</span></code> to the constructor
of <a class="reference internal" href="generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler" title="sklearn.preprocessing.StandardScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StandardScaler</span></code></a>.</p>
<div class="section" id="scaling-features-to-a-range">
<h3>6.3.1.1. Scaling features to a range<a class="headerlink" href="#scaling-features-to-a-range" title="Permalink to this headline">¶</a></h3>
<p>An alternative standardization is scaling features to
lie between a given minimum and maximum value, often between zero and one,
or so that the maximum absolute value of each feature is scaled to unit size.
This can be achieved using <a class="reference internal" href="generated/sklearn.preprocessing.MinMaxScaler.html#sklearn.preprocessing.MinMaxScaler" title="sklearn.preprocessing.MinMaxScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MinMaxScaler</span></code></a> or <a class="reference internal" href="generated/sklearn.preprocessing.MaxAbsScaler.html#sklearn.preprocessing.MaxAbsScaler" title="sklearn.preprocessing.MaxAbsScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxAbsScaler</span></code></a>,
respectively.</p>
<p>The motivation to use this scaling include robustness to very small
standard deviations of features and preserving zero entries in sparse data.</p>
<p>Here is an example to scale a toy data matrix to the <code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">1]</span></code> range:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X_train</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span> <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">2.</span><span class="p">],</span>
<span class="gp">... </span>                    <span class="p">[</span> <span class="mf">2.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">],</span>
<span class="gp">... </span>                    <span class="p">[</span> <span class="mf">0.</span><span class="p">,</span>  <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">]])</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">min_max_scaler</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">MinMaxScaler</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_train_minmax</span> <span class="o">=</span> <span class="n">min_max_scaler</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X_train</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_train_minmax</span>
<span class="go">array([[0.5       , 0.        , 1.        ],</span>
<span class="go">       [1.        , 0.5       , 0.33333333],</span>
<span class="go">       [0.        , 1.        , 0.        ]])</span>
</pre></div>
</div>
<p>The same instance of the transformer can then be applied to some new test data
unseen during the fit call: the same scaling and shifting operations will be
applied to be consistent with the transformation performed on the train data:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X_test</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span><span class="o">-</span><span class="mf">3.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">4.</span><span class="p">]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_test_minmax</span> <span class="o">=</span> <span class="n">min_max_scaler</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_test_minmax</span>
<span class="go">array([[-1.5       ,  0.        ,  1.66666667]])</span>
</pre></div>
</div>
<p>It is possible to introspect the scaler attributes to find about the exact
nature of the transformation learned on the training data:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">min_max_scaler</span><span class="o">.</span><span class="n">scale_</span>
<span class="go">array([0.5       , 0.5       , 0.33...])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">min_max_scaler</span><span class="o">.</span><span class="n">min_</span>
<span class="go">array([0.        , 0.5       , 0.33...])</span>
</pre></div>
</div>
<p>If <a class="reference internal" href="generated/sklearn.preprocessing.MinMaxScaler.html#sklearn.preprocessing.MinMaxScaler" title="sklearn.preprocessing.MinMaxScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MinMaxScaler</span></code></a> is given an explicit <code class="docutils literal notranslate"><span class="pre">feature_range=(min,</span> <span class="pre">max)</span></code> the
full formula is:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">X_std</span> <span class="o">=</span> <span class="p">(</span><span class="n">X</span> <span class="o">-</span> <span class="n">X</span><span class="o">.</span><span class="n">min</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span> <span class="o">/</span> <span class="p">(</span><span class="n">X</span><span class="o">.</span><span class="n">max</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="o">-</span> <span class="n">X</span><span class="o">.</span><span class="n">min</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">0</span><span class="p">))</span>

<span class="n">X_scaled</span> <span class="o">=</span> <span class="n">X_std</span> <span class="o">*</span> <span class="p">(</span><span class="nb">max</span> <span class="o">-</span> <span class="nb">min</span><span class="p">)</span> <span class="o">+</span> <span class="nb">min</span>
</pre></div>
</div>
<p><a class="reference internal" href="generated/sklearn.preprocessing.MaxAbsScaler.html#sklearn.preprocessing.MaxAbsScaler" title="sklearn.preprocessing.MaxAbsScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxAbsScaler</span></code></a> works in a very similar fashion, but scales in a way
that the training data lies within the range <code class="docutils literal notranslate"><span class="pre">[-1,</span> <span class="pre">1]</span></code> by dividing through
the largest maximum value in each feature. It is meant for data
that is already centered at zero or sparse data.</p>
<p>Here is how to use the toy data from the previous example with this scaler:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X_train</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span> <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">2.</span><span class="p">],</span>
<span class="gp">... </span>                    <span class="p">[</span> <span class="mf">2.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">],</span>
<span class="gp">... </span>                    <span class="p">[</span> <span class="mf">0.</span><span class="p">,</span>  <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">]])</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">max_abs_scaler</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">MaxAbsScaler</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_train_maxabs</span> <span class="o">=</span> <span class="n">max_abs_scaler</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X_train</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_train_maxabs</span>
<span class="go">array([[ 0.5, -1. ,  1. ],</span>
<span class="go">       [ 1. ,  0. ,  0. ],</span>
<span class="go">       [ 0. ,  1. , -0.5]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_test</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span> <span class="o">-</span><span class="mf">3.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">4.</span><span class="p">]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_test_maxabs</span> <span class="o">=</span> <span class="n">max_abs_scaler</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_test_maxabs</span>
<span class="go">array([[-1.5, -1. ,  2. ]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">max_abs_scaler</span><span class="o">.</span><span class="n">scale_</span>
<span class="go">array([2.,  1.,  2.])</span>
</pre></div>
</div>
<p>As with <a class="reference internal" href="generated/sklearn.preprocessing.scale.html#sklearn.preprocessing.scale" title="sklearn.preprocessing.scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">scale</span></code></a>, the module further provides convenience functions
<a class="reference internal" href="generated/sklearn.preprocessing.minmax_scale.html#sklearn.preprocessing.minmax_scale" title="sklearn.preprocessing.minmax_scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">minmax_scale</span></code></a> and <a class="reference internal" href="generated/sklearn.preprocessing.maxabs_scale.html#sklearn.preprocessing.maxabs_scale" title="sklearn.preprocessing.maxabs_scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">maxabs_scale</span></code></a> if you don’t want to create
an object.</p>
</div>
<div class="section" id="scaling-sparse-data">
<h3>6.3.1.2. Scaling sparse data<a class="headerlink" href="#scaling-sparse-data" title="Permalink to this headline">¶</a></h3>
<p>Centering sparse data would destroy the sparseness structure in the data, and
thus rarely is a sensible thing to do. However, it can make sense to scale
sparse inputs, especially if features are on different scales.</p>
<p><a class="reference internal" href="generated/sklearn.preprocessing.MaxAbsScaler.html#sklearn.preprocessing.MaxAbsScaler" title="sklearn.preprocessing.MaxAbsScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">MaxAbsScaler</span></code></a>  and <a class="reference internal" href="generated/sklearn.preprocessing.maxabs_scale.html#sklearn.preprocessing.maxabs_scale" title="sklearn.preprocessing.maxabs_scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">maxabs_scale</span></code></a> were specifically designed
for scaling sparse data, and are the recommended way to go about this.
However, <a class="reference internal" href="generated/sklearn.preprocessing.scale.html#sklearn.preprocessing.scale" title="sklearn.preprocessing.scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">scale</span></code></a> and <a class="reference internal" href="generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler" title="sklearn.preprocessing.StandardScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StandardScaler</span></code></a> can accept <code class="docutils literal notranslate"><span class="pre">scipy.sparse</span></code>
matrices  as input, as long as <code class="docutils literal notranslate"><span class="pre">with_mean=False</span></code> is explicitly passed
to the constructor. Otherwise a <code class="docutils literal notranslate"><span class="pre">ValueError</span></code> will be raised as
silently centering would break the sparsity and would often crash the
execution by allocating excessive amounts of memory unintentionally.
<a class="reference internal" href="generated/sklearn.preprocessing.RobustScaler.html#sklearn.preprocessing.RobustScaler" title="sklearn.preprocessing.RobustScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RobustScaler</span></code></a> cannot be fitted to sparse inputs, but you can use
the <code class="docutils literal notranslate"><span class="pre">transform</span></code> method on sparse inputs.</p>
<p>Note that the scalers accept both Compressed Sparse Rows and Compressed
Sparse Columns format (see <code class="docutils literal notranslate"><span class="pre">scipy.sparse.csr_matrix</span></code> and
<code class="docutils literal notranslate"><span class="pre">scipy.sparse.csc_matrix</span></code>). Any other sparse input will be <strong>converted to
the Compressed Sparse Rows representation</strong>.  To avoid unnecessary memory
copies, it is recommended to choose the CSR or CSC representation upstream.</p>
<p>Finally, if the centered data is expected to be small enough, explicitly
converting the input to an array using the <code class="docutils literal notranslate"><span class="pre">toarray</span></code> method of sparse matrices
is another option.</p>
</div>
<div class="section" id="scaling-data-with-outliers">
<h3>6.3.1.3. Scaling data with outliers<a class="headerlink" href="#scaling-data-with-outliers" title="Permalink to this headline">¶</a></h3>
<p>If your data contains many outliers, scaling using the mean and variance
of the data is likely to not work very well. In these cases, you can use
<a class="reference internal" href="generated/sklearn.preprocessing.robust_scale.html#sklearn.preprocessing.robust_scale" title="sklearn.preprocessing.robust_scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">robust_scale</span></code></a> and <a class="reference internal" href="generated/sklearn.preprocessing.RobustScaler.html#sklearn.preprocessing.RobustScaler" title="sklearn.preprocessing.RobustScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">RobustScaler</span></code></a> as drop-in replacements
instead. They use more robust estimates for the center and range of your
data.</p>
<div class="topic">
<p class="topic-title">References:</p>
<p>Further discussion on the importance of centering and scaling data is
available on this FAQ: <a class="reference external" href="http://www.faqs.org/faqs/ai-faq/neural-nets/part2/section-16.html">Should I normalize/standardize/rescale the data?</a></p>
</div>
<div class="topic">
<p class="topic-title">Scaling vs Whitening</p>
<p>It is sometimes not enough to center and scale the features
independently, since a downstream model can further make some assumption
on the linear independence of the features.</p>
<p>To address this issue you can use <a class="reference internal" href="generated/sklearn.decomposition.PCA.html#sklearn.decomposition.PCA" title="sklearn.decomposition.PCA"><code class="xref py py-class docutils literal notranslate"><span class="pre">sklearn.decomposition.PCA</span></code></a> with
<code class="docutils literal notranslate"><span class="pre">whiten=True</span></code> to further remove the linear correlation across features.</p>
</div>
<div class="topic">
<p class="topic-title">Scaling a 1D array</p>
<p>All above functions (i.e. <a class="reference internal" href="generated/sklearn.preprocessing.scale.html#sklearn.preprocessing.scale" title="sklearn.preprocessing.scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">scale</span></code></a>, <a class="reference internal" href="generated/sklearn.preprocessing.minmax_scale.html#sklearn.preprocessing.minmax_scale" title="sklearn.preprocessing.minmax_scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">minmax_scale</span></code></a>,
<a class="reference internal" href="generated/sklearn.preprocessing.maxabs_scale.html#sklearn.preprocessing.maxabs_scale" title="sklearn.preprocessing.maxabs_scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">maxabs_scale</span></code></a>, and <a class="reference internal" href="generated/sklearn.preprocessing.robust_scale.html#sklearn.preprocessing.robust_scale" title="sklearn.preprocessing.robust_scale"><code class="xref py py-func docutils literal notranslate"><span class="pre">robust_scale</span></code></a>) accept 1D array which can be
useful in some specific case.</p>
</div>
</div>
<div class="section" id="centering-kernel-matrices">
<span id="kernel-centering"></span><h3>6.3.1.4. Centering kernel matrices<a class="headerlink" href="#centering-kernel-matrices" title="Permalink to this headline">¶</a></h3>
<p>If you have a kernel matrix of a kernel <span class="math notranslate nohighlight">\(K\)</span> that computes a dot product
in a feature space defined by function <span class="math notranslate nohighlight">\(\phi\)</span>,
a <a class="reference internal" href="generated/sklearn.preprocessing.KernelCenterer.html#sklearn.preprocessing.KernelCenterer" title="sklearn.preprocessing.KernelCenterer"><code class="xref py py-class docutils literal notranslate"><span class="pre">KernelCenterer</span></code></a> can transform the kernel matrix
so that it contains inner products in the feature space
defined by <span class="math notranslate nohighlight">\(\phi\)</span> followed by removal of the mean in that space.</p>
</div>
</div>
<div class="section" id="non-linear-transformation">
<span id="preprocessing-transformer"></span><h2>6.3.2. Non-linear transformation<a class="headerlink" href="#non-linear-transformation" title="Permalink to this headline">¶</a></h2>
<p>Two types of transformations are available: quantile transforms and power
transforms. Both quantile and power transforms are based on monotonic
transformations of the features and thus preserve the rank of the values
along each feature.</p>
<p>Quantile transforms put all features into the same desired distribution based
on the formula <span class="math notranslate nohighlight">\(G^{-1}(F(X))\)</span> where <span class="math notranslate nohighlight">\(F\)</span> is the cumulative
distribution function of the feature and <span class="math notranslate nohighlight">\(G^{-1}\)</span> the
<a class="reference external" href="https://en.wikipedia.org/wiki/Quantile_function">quantile function</a> of the
desired output distribution <span class="math notranslate nohighlight">\(G\)</span>. This formula is using the two following
facts: (i) if <span class="math notranslate nohighlight">\(X\)</span> is a random variable with a continuous cumulative
distribution function <span class="math notranslate nohighlight">\(F\)</span> then <span class="math notranslate nohighlight">\(F(X)\)</span> is uniformly distributed on
<span class="math notranslate nohighlight">\([0,1]\)</span>; (ii) if <span class="math notranslate nohighlight">\(U\)</span> is a random variable with uniform distribution
on <span class="math notranslate nohighlight">\([0,1]\)</span> then <span class="math notranslate nohighlight">\(G^{-1}(U)\)</span> has distribution <span class="math notranslate nohighlight">\(G\)</span>. By performing
a rank transformation, a quantile transform smooths out unusual distributions
and is less influenced by outliers than scaling methods. It does, however,
distort correlations and distances within and across features.</p>
<p>Power transforms are a family of parametric transformations that aim to map
data from any distribution to as close to a Gaussian distribution.</p>
<div class="section" id="mapping-to-a-uniform-distribution">
<h3>6.3.2.1. Mapping to a Uniform distribution<a class="headerlink" href="#mapping-to-a-uniform-distribution" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="generated/sklearn.preprocessing.QuantileTransformer.html#sklearn.preprocessing.QuantileTransformer" title="sklearn.preprocessing.QuantileTransformer"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuantileTransformer</span></code></a> and <a class="reference internal" href="generated/sklearn.preprocessing.quantile_transform.html#sklearn.preprocessing.quantile_transform" title="sklearn.preprocessing.quantile_transform"><code class="xref py py-func docutils literal notranslate"><span class="pre">quantile_transform</span></code></a> provide a
non-parametric transformation to map the data to a uniform distribution
with values between 0 and 1:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn.datasets</span> <span class="kn">import</span> <span class="n">load_iris</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">train_test_split</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span><span class="p">,</span> <span class="n">y</span> <span class="o">=</span> <span class="n">load_iris</span><span class="p">(</span><span class="n">return_X_y</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="n">train_test_split</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">random_state</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">quantile_transformer</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">QuantileTransformer</span><span class="p">(</span><span class="n">random_state</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_train_trans</span> <span class="o">=</span> <span class="n">quantile_transformer</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X_train</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_test_trans</span> <span class="o">=</span> <span class="n">quantile_transformer</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">percentile</span><span class="p">(</span><span class="n">X_train</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">],</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">25</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">75</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span> 
<span class="go">array([ 4.3,  5.1,  5.8,  6.5,  7.9])</span>
</pre></div>
</div>
<p>This feature corresponds to the sepal length in cm. Once the quantile
transformation applied, those landmarks approach closely the percentiles
previously defined:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">percentile</span><span class="p">(</span><span class="n">X_train_trans</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">],</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">25</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">75</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span>
<span class="gp">... </span>
<span class="go">array([ 0.00... ,  0.24...,  0.49...,  0.73...,  0.99... ])</span>
</pre></div>
</div>
<p>This can be confirmed on a independent testing set with similar remarks:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">percentile</span><span class="p">(</span><span class="n">X_test</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">],</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">25</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">75</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span>
<span class="gp">... </span>
<span class="go">array([ 4.4  ,  5.125,  5.75 ,  6.175,  7.3  ])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">np</span><span class="o">.</span><span class="n">percentile</span><span class="p">(</span><span class="n">X_test_trans</span><span class="p">[:,</span> <span class="mi">0</span><span class="p">],</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">25</span><span class="p">,</span> <span class="mi">50</span><span class="p">,</span> <span class="mi">75</span><span class="p">,</span> <span class="mi">100</span><span class="p">])</span>
<span class="gp">... </span>
<span class="go">array([ 0.01...,  0.25...,  0.46...,  0.60... ,  0.94...])</span>
</pre></div>
</div>
</div>
<div class="section" id="mapping-to-a-gaussian-distribution">
<h3>6.3.2.2. Mapping to a Gaussian distribution<a class="headerlink" href="#mapping-to-a-gaussian-distribution" title="Permalink to this headline">¶</a></h3>
<p>In many modeling scenarios, normality of the features in a dataset is desirable.
Power transforms are a family of parametric, monotonic transformations that aim
to map data from any distribution to as close to a Gaussian distribution as
possible in order to stabilize variance and minimize skewness.</p>
<p><a class="reference internal" href="generated/sklearn.preprocessing.PowerTransformer.html#sklearn.preprocessing.PowerTransformer" title="sklearn.preprocessing.PowerTransformer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PowerTransformer</span></code></a> currently provides two such power transformations,
the Yeo-Johnson transform and the Box-Cox transform.</p>
<p>The Yeo-Johnson transform is given by:</p>
<div class="math notranslate nohighlight">
\[\begin{split}x_i^{(\lambda)} =
\begin{cases}
 [(x_i + 1)^\lambda - 1] / \lambda &amp; \text{if } \lambda \neq 0, x_i \geq 0, \\[8pt]
\ln{(x_i + 1)} &amp; \text{if } \lambda = 0, x_i \geq 0 \\[8pt]
-[(-x_i + 1)^{2 - \lambda} - 1] / (2 - \lambda) &amp; \text{if } \lambda \neq 2, x_i &lt; 0, \\[8pt]
 - \ln (- x_i + 1) &amp; \text{if } \lambda = 2, x_i &lt; 0
\end{cases}\end{split}\]</div>
<p>while the Box-Cox transform is given by:</p>
<div class="math notranslate nohighlight">
\[\begin{split}x_i^{(\lambda)} =
\begin{cases}
\dfrac{x_i^\lambda - 1}{\lambda} &amp; \text{if } \lambda \neq 0, \\[8pt]
\ln{(x_i)} &amp; \text{if } \lambda = 0,
\end{cases}\end{split}\]</div>
<p>Box-Cox can only be applied to strictly positive data. In both methods, the
transformation is parameterized by <span class="math notranslate nohighlight">\(\lambda\)</span>, which is determined through
maximum likelihood estimation. Here is an example of using Box-Cox to map
samples drawn from a lognormal distribution to a normal distribution:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">pt</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">PowerTransformer</span><span class="p">(</span><span class="n">method</span><span class="o">=</span><span class="s1">&#39;box-cox&#39;</span><span class="p">,</span> <span class="n">standardize</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_lognormal</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">RandomState</span><span class="p">(</span><span class="mi">616</span><span class="p">)</span><span class="o">.</span><span class="n">lognormal</span><span class="p">(</span><span class="n">size</span><span class="o">=</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_lognormal</span>
<span class="go">array([[1.28..., 1.18..., 0.84...],</span>
<span class="go">       [0.94..., 1.60..., 0.38...],</span>
<span class="go">       [1.35..., 0.21..., 1.09...]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">pt</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X_lognormal</span><span class="p">)</span>
<span class="go">array([[ 0.49...,  0.17..., -0.15...],</span>
<span class="go">       [-0.05...,  0.58..., -0.57...],</span>
<span class="go">       [ 0.69..., -0.84...,  0.10...]])</span>
</pre></div>
</div>
<p>While the above example sets the <code class="docutils literal notranslate"><span class="pre">standardize</span></code> option to <code class="docutils literal notranslate"><span class="pre">False</span></code>,
<a class="reference internal" href="generated/sklearn.preprocessing.PowerTransformer.html#sklearn.preprocessing.PowerTransformer" title="sklearn.preprocessing.PowerTransformer"><code class="xref py py-class docutils literal notranslate"><span class="pre">PowerTransformer</span></code></a> will apply zero-mean, unit-variance normalization
to the transformed output by default.</p>
<p>Below are examples of Box-Cox and Yeo-Johnson applied to various probability
distributions.  Note that when applied to certain distributions, the power
transforms achieve very Gaussian-like results, but with others, they are
ineffective. This highlights the importance of visualizing the data before and
after transformation.</p>
<div class="figure align-center">
<a class="reference external image-reference" href="../auto_examples/preprocessing/plot_map_data_to_normal.html"><img alt="modules/../auto_examples/preprocessing/images/sphx_glr_plot_map_data_to_normal_001.png" src="modules/../auto_examples/preprocessing/images/sphx_glr_plot_map_data_to_normal_001.png" /></a>
</div>
<p>It is also possible to map data to a normal distribution using
<a class="reference internal" href="generated/sklearn.preprocessing.QuantileTransformer.html#sklearn.preprocessing.QuantileTransformer" title="sklearn.preprocessing.QuantileTransformer"><code class="xref py py-class docutils literal notranslate"><span class="pre">QuantileTransformer</span></code></a> by setting <code class="docutils literal notranslate"><span class="pre">output_distribution='normal'</span></code>.
Using the earlier example with the iris dataset:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">quantile_transformer</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">QuantileTransformer</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">output_distribution</span><span class="o">=</span><span class="s1">&#39;normal&#39;</span><span class="p">,</span> <span class="n">random_state</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_trans</span> <span class="o">=</span> <span class="n">quantile_transformer</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">quantile_transformer</span><span class="o">.</span><span class="n">quantiles_</span>
<span class="go">array([[4.3, 2. , 1. , 0.1],</span>
<span class="go">       [4.4, 2.2, 1.1, 0.1],</span>
<span class="go">       [4.4, 2.2, 1.2, 0.1],</span>
<span class="go">       ...,</span>
<span class="go">       [7.7, 4.1, 6.7, 2.5],</span>
<span class="go">       [7.7, 4.2, 6.7, 2.5],</span>
<span class="go">       [7.9, 4.4, 6.9, 2.5]])</span>
</pre></div>
</div>
<p>Thus the median of the input becomes the mean of the output, centered at 0. The
normal output is clipped so that the input’s minimum and maximum —
corresponding to the 1e-7 and 1 - 1e-7 quantiles respectively — do not
become infinite under the transformation.</p>
</div>
</div>
<div class="section" id="normalization">
<span id="preprocessing-normalization"></span><h2>6.3.3. Normalization<a class="headerlink" href="#normalization" title="Permalink to this headline">¶</a></h2>
<p><strong>Normalization</strong> is the process of <strong>scaling individual samples to have
unit norm</strong>. This process can be useful if you plan to use a quadratic form
such as the dot-product or any other kernel to quantify the similarity
of any pair of samples.</p>
<p>This assumption is the base of the <a class="reference external" href="https://en.wikipedia.org/wiki/Vector_Space_Model">Vector Space Model</a> often used in text
classification and clustering contexts.</p>
<p>The function <a class="reference internal" href="generated/sklearn.preprocessing.normalize.html#sklearn.preprocessing.normalize" title="sklearn.preprocessing.normalize"><code class="xref py py-func docutils literal notranslate"><span class="pre">normalize</span></code></a> provides a quick and easy way to perform this
operation on a single array-like dataset, either using the <code class="docutils literal notranslate"><span class="pre">l1</span></code> or <code class="docutils literal notranslate"><span class="pre">l2</span></code>
norms:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="p">[[</span> <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">2.</span><span class="p">],</span>
<span class="gp">... </span>     <span class="p">[</span> <span class="mf">2.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">],</span>
<span class="gp">... </span>     <span class="p">[</span> <span class="mf">0.</span><span class="p">,</span>  <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X_normalized</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">normalize</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">norm</span><span class="o">=</span><span class="s1">&#39;l2&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">X_normalized</span>
<span class="go">array([[ 0.40..., -0.40...,  0.81...],</span>
<span class="go">       [ 1.  ...,  0.  ...,  0.  ...],</span>
<span class="go">       [ 0.  ...,  0.70..., -0.70...]])</span>
</pre></div>
</div>
<p>The <code class="docutils literal notranslate"><span class="pre">preprocessing</span></code> module further provides a utility class
<a class="reference internal" href="generated/sklearn.preprocessing.Normalizer.html#sklearn.preprocessing.Normalizer" title="sklearn.preprocessing.Normalizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Normalizer</span></code></a> that implements the same operation using the
<code class="docutils literal notranslate"><span class="pre">Transformer</span></code> API (even though the <code class="docutils literal notranslate"><span class="pre">fit</span></code> method is useless in this case:
the class is stateless as this operation treats samples independently).</p>
<p>This class is hence suitable for use in the early steps of a
<a class="reference internal" href="generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline" title="sklearn.pipeline.Pipeline"><code class="xref py py-class docutils literal notranslate"><span class="pre">sklearn.pipeline.Pipeline</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">normalizer</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">Normalizer</span><span class="p">()</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>  <span class="c1"># fit does nothing</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">normalizer</span>
<span class="go">Normalizer()</span>
</pre></div>
</div>
<p>The normalizer instance can then be used on sample vectors as any transformer:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">normalizer</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">array([[ 0.40..., -0.40...,  0.81...],</span>
<span class="go">       [ 1.  ...,  0.  ...,  0.  ...],</span>
<span class="go">       [ 0.  ...,  0.70..., -0.70...]])</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">normalizer</span><span class="o">.</span><span class="n">transform</span><span class="p">([[</span><span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">1.</span><span class="p">,</span> <span class="mf">0.</span><span class="p">]])</span>
<span class="go">array([[-0.70...,  0.70...,  0.  ...]])</span>
</pre></div>
</div>
<p>Note: L2 normalization is also known as spatial sign preprocessing.</p>
<div class="topic">
<p class="topic-title">Sparse input</p>
<p><a class="reference internal" href="generated/sklearn.preprocessing.normalize.html#sklearn.preprocessing.normalize" title="sklearn.preprocessing.normalize"><code class="xref py py-func docutils literal notranslate"><span class="pre">normalize</span></code></a> and <a class="reference internal" href="generated/sklearn.preprocessing.Normalizer.html#sklearn.preprocessing.Normalizer" title="sklearn.preprocessing.Normalizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Normalizer</span></code></a> accept <strong>both dense array-like
and sparse matrices from scipy.sparse as input</strong>.</p>
<p>For sparse input the data is <strong>converted to the Compressed Sparse Rows
representation</strong> (see <code class="docutils literal notranslate"><span class="pre">scipy.sparse.csr_matrix</span></code>) before being fed to
efficient Cython routines. To avoid unnecessary memory copies, it is
recommended to choose the CSR representation upstream.</p>
</div>
</div>
<div class="section" id="encoding-categorical-features">
<span id="preprocessing-categorical-features"></span><h2>6.3.4. Encoding categorical features<a class="headerlink" href="#encoding-categorical-features" title="Permalink to this headline">¶</a></h2>
<p>Often features are not given as continuous values but categorical.
For example a person could have features <code class="docutils literal notranslate"><span class="pre">[&quot;male&quot;,</span> <span class="pre">&quot;female&quot;]</span></code>,
<code class="docutils literal notranslate"><span class="pre">[&quot;from</span> <span class="pre">Europe&quot;,</span> <span class="pre">&quot;from</span> <span class="pre">US&quot;,</span> <span class="pre">&quot;from</span> <span class="pre">Asia&quot;]</span></code>,
<code class="docutils literal notranslate"><span class="pre">[&quot;uses</span> <span class="pre">Firefox&quot;,</span> <span class="pre">&quot;uses</span> <span class="pre">Chrome&quot;,</span> <span class="pre">&quot;uses</span> <span class="pre">Safari&quot;,</span> <span class="pre">&quot;uses</span> <span class="pre">Internet</span> <span class="pre">Explorer&quot;]</span></code>.
Such features can be efficiently coded as integers, for instance
<code class="docutils literal notranslate"><span class="pre">[&quot;male&quot;,</span> <span class="pre">&quot;from</span> <span class="pre">US&quot;,</span> <span class="pre">&quot;uses</span> <span class="pre">Internet</span> <span class="pre">Explorer&quot;]</span></code> could be expressed as
<code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">1,</span> <span class="pre">3]</span></code> while <code class="docutils literal notranslate"><span class="pre">[&quot;female&quot;,</span> <span class="pre">&quot;from</span> <span class="pre">Asia&quot;,</span> <span class="pre">&quot;uses</span> <span class="pre">Chrome&quot;]</span></code> would be
<code class="docutils literal notranslate"><span class="pre">[1,</span> <span class="pre">2,</span> <span class="pre">1]</span></code>.</p>
<p>To convert categorical features to such integer codes, we can use the
<a class="reference internal" href="generated/sklearn.preprocessing.OrdinalEncoder.html#sklearn.preprocessing.OrdinalEncoder" title="sklearn.preprocessing.OrdinalEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">OrdinalEncoder</span></code></a>. This estimator transforms each categorical feature to one
new feature of integers (0 to n_categories - 1):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">OrdinalEncoder</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;male&#39;</span><span class="p">,</span> <span class="s1">&#39;from US&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">],</span> <span class="p">[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from Europe&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Firefox&#39;</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">OrdinalEncoder()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">transform</span><span class="p">([[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from US&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">]])</span>
<span class="go">array([[0., 1., 1.]])</span>
</pre></div>
</div>
<p>Such integer representation can, however, not be used directly with all
scikit-learn estimators, as these expect continuous input, and would interpret
the categories as being ordered, which is often not desired (i.e. the set of
browsers was ordered arbitrarily).</p>
<p>Another possibility to convert categorical features to features that can be used
with scikit-learn estimators is to use a one-of-K, also known as one-hot or
dummy encoding.
This type of encoding can be obtained with the <a class="reference internal" href="generated/sklearn.preprocessing.OneHotEncoder.html#sklearn.preprocessing.OneHotEncoder" title="sklearn.preprocessing.OneHotEncoder"><code class="xref py py-class docutils literal notranslate"><span class="pre">OneHotEncoder</span></code></a>,
which transforms each categorical feature with
<code class="docutils literal notranslate"><span class="pre">n_categories</span></code> possible values into <code class="docutils literal notranslate"><span class="pre">n_categories</span></code> binary features, with
one of them 1, and all others 0.</p>
<p>Continuing the example above:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">OneHotEncoder</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;male&#39;</span><span class="p">,</span> <span class="s1">&#39;from US&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">],</span> <span class="p">[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from Europe&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Firefox&#39;</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">OneHotEncoder()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">transform</span><span class="p">([[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from US&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">],</span>
<span class="gp">... </span>               <span class="p">[</span><span class="s1">&#39;male&#39;</span><span class="p">,</span> <span class="s1">&#39;from Europe&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">]])</span><span class="o">.</span><span class="n">toarray</span><span class="p">()</span>
<span class="go">array([[1., 0., 0., 1., 0., 1.],</span>
<span class="go">       [0., 1., 1., 0., 0., 1.]])</span>
</pre></div>
</div>
<p>By default, the values each feature can take is inferred automatically
from the dataset and can be found in the <code class="docutils literal notranslate"><span class="pre">categories_</span></code> attribute:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">categories_</span>
<span class="go">[array([&#39;female&#39;, &#39;male&#39;], dtype=object), array([&#39;from Europe&#39;, &#39;from US&#39;], dtype=object), array([&#39;uses Firefox&#39;, &#39;uses Safari&#39;], dtype=object)]</span>
</pre></div>
</div>
<p>It is possible to specify this explicitly using the parameter <code class="docutils literal notranslate"><span class="pre">categories</span></code>.
There are two genders, four possible continents and four web browsers in our
dataset:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">genders</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;male&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">locations</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;from Africa&#39;</span><span class="p">,</span> <span class="s1">&#39;from Asia&#39;</span><span class="p">,</span> <span class="s1">&#39;from Europe&#39;</span><span class="p">,</span> <span class="s1">&#39;from US&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">browsers</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;uses Chrome&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Firefox&#39;</span><span class="p">,</span> <span class="s1">&#39;uses IE&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">OneHotEncoder</span><span class="p">(</span><span class="n">categories</span><span class="o">=</span><span class="p">[</span><span class="n">genders</span><span class="p">,</span> <span class="n">locations</span><span class="p">,</span> <span class="n">browsers</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Note that for there are missing categorical values for the 2nd and 3rd</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># feature</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;male&#39;</span><span class="p">,</span> <span class="s1">&#39;from US&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">],</span> <span class="p">[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from Europe&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Firefox&#39;</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">OneHotEncoder(categories=[[&#39;female&#39;, &#39;male&#39;],</span>
<span class="go">                          [&#39;from Africa&#39;, &#39;from Asia&#39;, &#39;from Europe&#39;,</span>
<span class="go">                           &#39;from US&#39;],</span>
<span class="go">                          [&#39;uses Chrome&#39;, &#39;uses Firefox&#39;, &#39;uses IE&#39;,</span>
<span class="go">                           &#39;uses Safari&#39;]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">transform</span><span class="p">([[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from Asia&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Chrome&#39;</span><span class="p">]])</span><span class="o">.</span><span class="n">toarray</span><span class="p">()</span>
<span class="go">array([[1., 0., 0., 1., 0., 0., 1., 0., 0., 0.]])</span>
</pre></div>
</div>
<p>If there is a possibility that the training data might have missing categorical
features, it can often be better to specify <code class="docutils literal notranslate"><span class="pre">handle_unknown='ignore'</span></code> instead
of setting the <code class="docutils literal notranslate"><span class="pre">categories</span></code> manually as above. When
<code class="docutils literal notranslate"><span class="pre">handle_unknown='ignore'</span></code> is specified and unknown categories are encountered
during transform, no error will be raised but the resulting one-hot encoded
columns for this feature will be all zeros
(<code class="docutils literal notranslate"><span class="pre">handle_unknown='ignore'</span></code> is only supported for one-hot encoding):</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">OneHotEncoder</span><span class="p">(</span><span class="n">handle_unknown</span><span class="o">=</span><span class="s1">&#39;ignore&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;male&#39;</span><span class="p">,</span> <span class="s1">&#39;from US&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">],</span> <span class="p">[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from Europe&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Firefox&#39;</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">OneHotEncoder(handle_unknown=&#39;ignore&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">enc</span><span class="o">.</span><span class="n">transform</span><span class="p">([[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from Asia&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Chrome&#39;</span><span class="p">]])</span><span class="o">.</span><span class="n">toarray</span><span class="p">()</span>
<span class="go">array([[1., 0., 0., 0., 0., 0.]])</span>
</pre></div>
</div>
<p>It is also possible to encode each column into <code class="docutils literal notranslate"><span class="pre">n_categories</span> <span class="pre">-</span> <span class="pre">1</span></code> columns
instead of <code class="docutils literal notranslate"><span class="pre">n_categories</span></code> columns by using the <code class="docutils literal notranslate"><span class="pre">drop</span></code> parameter. This
parameter allows the user to specify a category for each feature to be dropped.
This is useful to avoid co-linearity in the input matrix in some classifiers.
Such functionality is useful, for example, when using non-regularized
regression (<a class="reference internal" href="generated/sklearn.linear_model.LinearRegression.html#sklearn.linear_model.LinearRegression" title="sklearn.linear_model.LinearRegression"><code class="xref py py-class docutils literal notranslate"><span class="pre">LinearRegression</span></code></a>),
since co-linearity would cause the covariance matrix to be non-invertible.
When this paramenter is not None, <code class="docutils literal notranslate"><span class="pre">handle_unknown</span></code> must be set to
<code class="docutils literal notranslate"><span class="pre">error</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="p">[[</span><span class="s1">&#39;male&#39;</span><span class="p">,</span> <span class="s1">&#39;from US&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Safari&#39;</span><span class="p">],</span> <span class="p">[</span><span class="s1">&#39;female&#39;</span><span class="p">,</span> <span class="s1">&#39;from Europe&#39;</span><span class="p">,</span> <span class="s1">&#39;uses Firefox&#39;</span><span class="p">]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">drop_enc</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">OneHotEncoder</span><span class="p">(</span><span class="n">drop</span><span class="o">=</span><span class="s1">&#39;first&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">drop_enc</span><span class="o">.</span><span class="n">categories_</span>
<span class="go">[array([&#39;female&#39;, &#39;male&#39;], dtype=object), array([&#39;from Europe&#39;, &#39;from US&#39;], dtype=object), array([&#39;uses Firefox&#39;, &#39;uses Safari&#39;], dtype=object)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">drop_enc</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span><span class="o">.</span><span class="n">toarray</span><span class="p">()</span>
<span class="go">array([[1., 1., 1.],</span>
<span class="go">       [0., 0., 0.]])</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="feature_extraction.html#dict-feature-extraction"><span class="std std-ref">Loading features from dicts</span></a> for categorical features that are represented
as a dict, not as scalars.</p>
</div>
<div class="section" id="discretization">
<span id="preprocessing-discretization"></span><h2>6.3.5. Discretization<a class="headerlink" href="#discretization" title="Permalink to this headline">¶</a></h2>
<p><a class="reference external" href="https://en.wikipedia.org/wiki/Discretization_of_continuous_features">Discretization</a>
(otherwise known as quantization or binning) provides a way to partition continuous
features into discrete values. Certain datasets with continuous features
may benefit from discretization, because discretization can transform the dataset
of continuous attributes to one with only nominal attributes.</p>
<p>One-hot encoded discretized features can make a model more expressive, while
maintaining interpretability. For instance, pre-processing with a discretizer
can introduce nonlinearity to linear models.</p>
<div class="section" id="k-bins-discretization">
<h3>6.3.5.1. K-bins discretization<a class="headerlink" href="#k-bins-discretization" title="Permalink to this headline">¶</a></h3>
<p><a class="reference internal" href="generated/sklearn.preprocessing.KBinsDiscretizer.html#sklearn.preprocessing.KBinsDiscretizer" title="sklearn.preprocessing.KBinsDiscretizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">KBinsDiscretizer</span></code></a> discretizes features into <code class="docutils literal notranslate"><span class="pre">k</span></code> bins:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span> <span class="o">-</span><span class="mf">3.</span><span class="p">,</span> <span class="mf">5.</span><span class="p">,</span> <span class="mi">15</span> <span class="p">],</span>
<span class="gp">... </span>              <span class="p">[</span>  <span class="mf">0.</span><span class="p">,</span> <span class="mf">6.</span><span class="p">,</span> <span class="mi">14</span> <span class="p">],</span>
<span class="gp">... </span>              <span class="p">[</span>  <span class="mf">6.</span><span class="p">,</span> <span class="mf">3.</span><span class="p">,</span> <span class="mi">11</span> <span class="p">]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">est</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">KBinsDiscretizer</span><span class="p">(</span><span class="n">n_bins</span><span class="o">=</span><span class="p">[</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">2</span><span class="p">],</span> <span class="n">encode</span><span class="o">=</span><span class="s1">&#39;ordinal&#39;</span><span class="p">)</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
</pre></div>
</div>
<p>By default the output is one-hot encoded into a sparse matrix
(See <a class="reference internal" href="#preprocessing-categorical-features"><span class="std std-ref">Encoding categorical features</span></a>)
and this can be configured with the <code class="docutils literal notranslate"><span class="pre">encode</span></code> parameter.
For each feature, the bin edges are computed during <code class="docutils literal notranslate"><span class="pre">fit</span></code> and together with
the number of bins, they will define the intervals. Therefore, for the current
example, these intervals are defined as:</p>
<blockquote>
<div><ul class="simple">
<li><p>feature 1: <span class="math notranslate nohighlight">\({[-\infty, -1), [-1, 2), [2, \infty)}\)</span></p></li>
<li><p>feature 2: <span class="math notranslate nohighlight">\({[-\infty, 5), [5, \infty)}\)</span></p></li>
<li><p>feature 3: <span class="math notranslate nohighlight">\({[-\infty, 14), [14, \infty)}\)</span></p></li>
</ul>
</div></blockquote>
<p>Based on these bin intervals, <code class="docutils literal notranslate"><span class="pre">X</span></code> is transformed as follows:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">est</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>                      
<span class="go">array([[ 0., 1., 1.],</span>
<span class="go">       [ 1., 1., 1.],</span>
<span class="go">       [ 2., 0., 0.]])</span>
</pre></div>
</div>
<p>The resulting dataset contains ordinal attributes which can be further used
in a <a class="reference internal" href="generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline" title="sklearn.pipeline.Pipeline"><code class="xref py py-class docutils literal notranslate"><span class="pre">sklearn.pipeline.Pipeline</span></code></a>.</p>
<p>Discretization is similar to constructing histograms for continuous data.
However, histograms focus on counting features which fall into particular
bins, whereas discretization focuses on assigning feature values to these bins.</p>
<p><a class="reference internal" href="generated/sklearn.preprocessing.KBinsDiscretizer.html#sklearn.preprocessing.KBinsDiscretizer" title="sklearn.preprocessing.KBinsDiscretizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">KBinsDiscretizer</span></code></a> implements different binning strategies, which can be
selected with the <code class="docutils literal notranslate"><span class="pre">strategy</span></code> parameter. The ‘uniform’ strategy uses
constant-width bins. The ‘quantile’ strategy uses the quantiles values to have
equally populated bins in each feature. The ‘kmeans’ strategy defines bins based
on a k-means clustering procedure performed on each feature independently.</p>
<div class="topic">
<p class="topic-title">Examples:</p>
<ul class="simple">
<li><p><a class="reference internal" href="../auto_examples/preprocessing/plot_discretization.html#sphx-glr-auto-examples-preprocessing-plot-discretization-py"><span class="std std-ref">Using KBinsDiscretizer to discretize continuous features</span></a></p></li>
<li><p><a class="reference internal" href="../auto_examples/preprocessing/plot_discretization_classification.html#sphx-glr-auto-examples-preprocessing-plot-discretization-classification-py"><span class="std std-ref">Feature discretization</span></a></p></li>
<li><p><a class="reference internal" href="../auto_examples/preprocessing/plot_discretization_strategies.html#sphx-glr-auto-examples-preprocessing-plot-discretization-strategies-py"><span class="std std-ref">Demonstrating the different strategies of KBinsDiscretizer</span></a></p></li>
</ul>
</div>
</div>
<div class="section" id="feature-binarization">
<span id="preprocessing-binarization"></span><h3>6.3.5.2. Feature binarization<a class="headerlink" href="#feature-binarization" title="Permalink to this headline">¶</a></h3>
<p><strong>Feature binarization</strong> is the process of <strong>thresholding numerical
features to get boolean values</strong>. This can be useful for downstream
probabilistic estimators that make assumption that the input data
is distributed according to a multi-variate <a class="reference external" href="https://en.wikipedia.org/wiki/Bernoulli_distribution">Bernoulli distribution</a>. For instance,
this is the case for the <a class="reference internal" href="generated/sklearn.neural_network.BernoulliRBM.html#sklearn.neural_network.BernoulliRBM" title="sklearn.neural_network.BernoulliRBM"><code class="xref py py-class docutils literal notranslate"><span class="pre">sklearn.neural_network.BernoulliRBM</span></code></a>.</p>
<p>It is also common among the text processing community to use binary
feature values (probably to simplify the probabilistic reasoning) even
if normalized counts (a.k.a. term frequencies) or TF-IDF valued features
often perform slightly better in practice.</p>
<p>As for the <a class="reference internal" href="generated/sklearn.preprocessing.Normalizer.html#sklearn.preprocessing.Normalizer" title="sklearn.preprocessing.Normalizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Normalizer</span></code></a>, the utility class
<a class="reference internal" href="generated/sklearn.preprocessing.Binarizer.html#sklearn.preprocessing.Binarizer" title="sklearn.preprocessing.Binarizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Binarizer</span></code></a> is meant to be used in the early stages of
<a class="reference internal" href="generated/sklearn.pipeline.Pipeline.html#sklearn.pipeline.Pipeline" title="sklearn.pipeline.Pipeline"><code class="xref py py-class docutils literal notranslate"><span class="pre">sklearn.pipeline.Pipeline</span></code></a>. The <code class="docutils literal notranslate"><span class="pre">fit</span></code> method does nothing
as each sample is treated independently of others:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="p">[[</span> <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">,</span>  <span class="mf">2.</span><span class="p">],</span>
<span class="gp">... </span>     <span class="p">[</span> <span class="mf">2.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">,</span>  <span class="mf">0.</span><span class="p">],</span>
<span class="gp">... </span>     <span class="p">[</span> <span class="mf">0.</span><span class="p">,</span>  <span class="mf">1.</span><span class="p">,</span> <span class="o">-</span><span class="mf">1.</span><span class="p">]]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">binarizer</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">Binarizer</span><span class="p">()</span><span class="o">.</span><span class="n">fit</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>  <span class="c1"># fit does nothing</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">binarizer</span>
<span class="go">Binarizer()</span>

<span class="gp">&gt;&gt;&gt; </span><span class="n">binarizer</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">array([[1., 0., 1.],</span>
<span class="go">       [1., 0., 0.],</span>
<span class="go">       [0., 1., 0.]])</span>
</pre></div>
</div>
<p>It is possible to adjust the threshold of the binarizer:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">binarizer</span> <span class="o">=</span> <span class="n">preprocessing</span><span class="o">.</span><span class="n">Binarizer</span><span class="p">(</span><span class="n">threshold</span><span class="o">=</span><span class="mf">1.1</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">binarizer</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">array([[0., 0., 1.],</span>
<span class="go">       [1., 0., 0.],</span>
<span class="go">       [0., 0., 0.]])</span>
</pre></div>
</div>
<p>As for the <a class="reference internal" href="generated/sklearn.preprocessing.StandardScaler.html#sklearn.preprocessing.StandardScaler" title="sklearn.preprocessing.StandardScaler"><code class="xref py py-class docutils literal notranslate"><span class="pre">StandardScaler</span></code></a> and <a class="reference internal" href="generated/sklearn.preprocessing.Normalizer.html#sklearn.preprocessing.Normalizer" title="sklearn.preprocessing.Normalizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Normalizer</span></code></a> classes, the
preprocessing module provides a companion function <a class="reference internal" href="generated/sklearn.preprocessing.binarize.html#sklearn.preprocessing.binarize" title="sklearn.preprocessing.binarize"><code class="xref py py-func docutils literal notranslate"><span class="pre">binarize</span></code></a>
to be used when the transformer API is not necessary.</p>
<p>Note that the <a class="reference internal" href="generated/sklearn.preprocessing.Binarizer.html#sklearn.preprocessing.Binarizer" title="sklearn.preprocessing.Binarizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Binarizer</span></code></a> is similar to the <a class="reference internal" href="generated/sklearn.preprocessing.KBinsDiscretizer.html#sklearn.preprocessing.KBinsDiscretizer" title="sklearn.preprocessing.KBinsDiscretizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">KBinsDiscretizer</span></code></a>
when <code class="docutils literal notranslate"><span class="pre">k</span> <span class="pre">=</span> <span class="pre">2</span></code>, and when the bin edge is at the value <code class="docutils literal notranslate"><span class="pre">threshold</span></code>.</p>
<div class="topic">
<p class="topic-title">Sparse input</p>
<p><a class="reference internal" href="generated/sklearn.preprocessing.binarize.html#sklearn.preprocessing.binarize" title="sklearn.preprocessing.binarize"><code class="xref py py-func docutils literal notranslate"><span class="pre">binarize</span></code></a> and <a class="reference internal" href="generated/sklearn.preprocessing.Binarizer.html#sklearn.preprocessing.Binarizer" title="sklearn.preprocessing.Binarizer"><code class="xref py py-class docutils literal notranslate"><span class="pre">Binarizer</span></code></a> accept <strong>both dense array-like
and sparse matrices from scipy.sparse as input</strong>.</p>
<p>For sparse input the data is <strong>converted to the Compressed Sparse Rows
representation</strong> (see <code class="docutils literal notranslate"><span class="pre">scipy.sparse.csr_matrix</span></code>).
To avoid unnecessary memory copies, it is recommended to choose the CSR
representation upstream.</p>
</div>
</div>
</div>
<div class="section" id="imputation-of-missing-values">
<span id="imputation"></span><h2>6.3.6. Imputation of missing values<a class="headerlink" href="#imputation-of-missing-values" title="Permalink to this headline">¶</a></h2>
<p>Tools for imputing missing values are discussed at <a class="reference internal" href="impute.html#impute"><span class="std std-ref">Imputation of missing values</span></a>.</p>
</div>
<div class="section" id="generating-polynomial-features">
<span id="polynomial-features"></span><h2>6.3.7. Generating polynomial features<a class="headerlink" href="#generating-polynomial-features" title="Permalink to this headline">¶</a></h2>
<p>Often it’s useful to add complexity to the model by considering nonlinear features of the input data. A simple and common method to use is polynomial features, which can get features’ high-order and interaction terms. It is implemented in <a class="reference internal" href="generated/sklearn.preprocessing.PolynomialFeatures.html#sklearn.preprocessing.PolynomialFeatures" title="sklearn.preprocessing.PolynomialFeatures"><code class="xref py py-class docutils literal notranslate"><span class="pre">PolynomialFeatures</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn.preprocessing</span> <span class="kn">import</span> <span class="n">PolynomialFeatures</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">6</span><span class="p">)</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span>
<span class="go">array([[0, 1],</span>
<span class="go">       [2, 3],</span>
<span class="go">       [4, 5]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">poly</span> <span class="o">=</span> <span class="n">PolynomialFeatures</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">poly</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">array([[ 1.,  0.,  1.,  0.,  0.,  1.],</span>
<span class="go">       [ 1.,  2.,  3.,  4.,  6.,  9.],</span>
<span class="go">       [ 1.,  4.,  5., 16., 20., 25.]])</span>
</pre></div>
</div>
<p>The features of X have been transformed from <span class="math notranslate nohighlight">\((X_1, X_2)\)</span> to <span class="math notranslate nohighlight">\((1, X_1, X_2, X_1^2, X_1X_2, X_2^2)\)</span>.</p>
<p>In some cases, only interaction terms among features are required, and it can be gotten with the setting <code class="docutils literal notranslate"><span class="pre">interaction_only=True</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">9</span><span class="p">)</span><span class="o">.</span><span class="n">reshape</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span>
<span class="go">array([[0, 1, 2],</span>
<span class="go">       [3, 4, 5],</span>
<span class="go">       [6, 7, 8]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">poly</span> <span class="o">=</span> <span class="n">PolynomialFeatures</span><span class="p">(</span><span class="n">degree</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">interaction_only</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">poly</span><span class="o">.</span><span class="n">fit_transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">array([[  1.,   0.,   1.,   2.,   0.,   0.,   2.,   0.],</span>
<span class="go">       [  1.,   3.,   4.,   5.,  12.,  15.,  20.,  60.],</span>
<span class="go">       [  1.,   6.,   7.,   8.,  42.,  48.,  56., 336.]])</span>
</pre></div>
</div>
<p>The features of X have been transformed from <span class="math notranslate nohighlight">\((X_1, X_2, X_3)\)</span> to <span class="math notranslate nohighlight">\((1, X_1, X_2, X_3, X_1X_2, X_1X_3, X_2X_3, X_1X_2X_3)\)</span>.</p>
<p>Note that polynomial features are used implicitly in <a class="reference external" href="https://en.wikipedia.org/wiki/Kernel_method">kernel methods</a> (e.g., <a class="reference internal" href="generated/sklearn.svm.SVC.html#sklearn.svm.SVC" title="sklearn.svm.SVC"><code class="xref py py-class docutils literal notranslate"><span class="pre">sklearn.svm.SVC</span></code></a>, <a class="reference internal" href="generated/sklearn.decomposition.KernelPCA.html#sklearn.decomposition.KernelPCA" title="sklearn.decomposition.KernelPCA"><code class="xref py py-class docutils literal notranslate"><span class="pre">sklearn.decomposition.KernelPCA</span></code></a>) when using polynomial <a class="reference internal" href="svm.html#svm-kernels"><span class="std std-ref">Kernel functions</span></a>.</p>
<p>See <a class="reference internal" href="../auto_examples/linear_model/plot_polynomial_interpolation.html#sphx-glr-auto-examples-linear-model-plot-polynomial-interpolation-py"><span class="std std-ref">Polynomial interpolation</span></a> for Ridge regression using created polynomial features.</p>
</div>
<div class="section" id="custom-transformers">
<span id="function-transformer"></span><h2>6.3.8. Custom transformers<a class="headerlink" href="#custom-transformers" title="Permalink to this headline">¶</a></h2>
<p>Often, you will want to convert an existing Python function into a transformer
to assist in data cleaning or processing. You can implement a transformer from
an arbitrary function with <a class="reference internal" href="generated/sklearn.preprocessing.FunctionTransformer.html#sklearn.preprocessing.FunctionTransformer" title="sklearn.preprocessing.FunctionTransformer"><code class="xref py py-class docutils literal notranslate"><span class="pre">FunctionTransformer</span></code></a>. For example, to build
a transformer that applies a log transformation in a pipeline, do:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="gp">&gt;&gt;&gt; </span><span class="kn">from</span> <span class="nn">sklearn.preprocessing</span> <span class="kn">import</span> <span class="n">FunctionTransformer</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">transformer</span> <span class="o">=</span> <span class="n">FunctionTransformer</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">log1p</span><span class="p">,</span> <span class="n">validate</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">X</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">],</span> <span class="p">[</span><span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">]])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">transformer</span><span class="o">.</span><span class="n">transform</span><span class="p">(</span><span class="n">X</span><span class="p">)</span>
<span class="go">array([[0.        , 0.69314718],</span>
<span class="go">       [1.09861229, 1.38629436]])</span>
</pre></div>
</div>
<p>You can ensure that <code class="docutils literal notranslate"><span class="pre">func</span></code> and <code class="docutils literal notranslate"><span class="pre">inverse_func</span></code> are the inverse of each other
by setting <code class="docutils literal notranslate"><span class="pre">check_inverse=True</span></code> and calling <code class="docutils literal notranslate"><span class="pre">fit</span></code> before
<code class="docutils literal notranslate"><span class="pre">transform</span></code>. Please note that a warning is raised and can be turned into an
error with a <code class="docutils literal notranslate"><span class="pre">filterwarnings</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">warnings</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">warnings</span><span class="o">.</span><span class="n">filterwarnings</span><span class="p">(</span><span class="s2">&quot;error&quot;</span><span class="p">,</span> <span class="n">message</span><span class="o">=</span><span class="s2">&quot;.*check_inverse*.&quot;</span><span class="p">,</span>
<span class="gp">... </span>                        <span class="n">category</span><span class="o">=</span><span class="ne">UserWarning</span><span class="p">,</span> <span class="n">append</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
</pre></div>
</div>
<p>For a full code example that demonstrates using a <a class="reference internal" href="generated/sklearn.preprocessing.FunctionTransformer.html#sklearn.preprocessing.FunctionTransformer" title="sklearn.preprocessing.FunctionTransformer"><code class="xref py py-class docutils literal notranslate"><span class="pre">FunctionTransformer</span></code></a>
to do custom feature selection,
see <a class="reference internal" href="../auto_examples/preprocessing/plot_function_transformer.html#sphx-glr-auto-examples-preprocessing-plot-function-transformer-py"><span class="std std-ref">Using FunctionTransformer to select columns</span></a></p>
</div>
</div>


      </div>
    <div class="container">
      <footer class="sk-content-footer">
            &copy; 2007 - 2019, scikit-learn developers (BSD License).
          <a href="../_sources/modules/preprocessing.rst.txt" rel="nofollow">Show this page source</a>
      </footer>
    </div>
  </div>
</div>
<script src="../_static/js/vendor/bootstrap.min.js"></script>

<script>
    window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
    ga('create', 'UA-22606712-2', 'auto');
    ga('set', 'anonymizeIp', true);
    ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>


<script>
$(document).ready(function() {
    /* Add a [>>>] button on the top-right corner of code samples to hide
     * the >>> and ... prompts and the output and thus make the code
     * copyable. */
    var div = $('.highlight-python .highlight,' +
                '.highlight-python3 .highlight,' +
                '.highlight-pycon .highlight,' +
		'.highlight-default .highlight')
    var pre = div.find('pre');

    // get the styles from the current theme
    pre.parent().parent().css('position', 'relative');
    var hide_text = 'Hide prompts and outputs';
    var show_text = 'Show prompts and outputs';

    // create and add the button to all the code blocks that contain >>>
    div.each(function(index) {
        var jthis = $(this);
        if (jthis.find('.gp').length > 0) {
            var button = $('<span class="copybutton">&gt;&gt;&gt;</span>');
            button.attr('title', hide_text);
            button.data('hidden', 'false');
            jthis.prepend(button);
        }
        // tracebacks (.gt) contain bare text elements that need to be
        // wrapped in a span to work with .nextUntil() (see later)
        jthis.find('pre:has(.gt)').contents().filter(function() {
            return ((this.nodeType == 3) && (this.data.trim().length > 0));
        }).wrap('<span>');
    });

    // define the behavior of the button when it's clicked
    $('.copybutton').click(function(e){
        e.preventDefault();
        var button = $(this);
        if (button.data('hidden') === 'false') {
            // hide the code output
            button.parent().find('.go, .gp, .gt').hide();
            button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'hidden');
            button.css('text-decoration', 'line-through');
            button.attr('title', show_text);
            button.data('hidden', 'true');
        } else {
            // show the code output
            button.parent().find('.go, .gp, .gt').show();
            button.next('pre').find('.gt').nextUntil('.gp, .go').css('visibility', 'visible');
            button.css('text-decoration', 'none');
            button.attr('title', hide_text);
            button.data('hidden', 'false');
        }
    });

	/*** Add permalink buttons next to glossary terms ***/
	$('dl.glossary > dt[id]').append(function() {
		return ('<a class="headerlink" href="#' +
			    this.getAttribute('id') +
			    '" title="Permalink to this term">¶</a>');
	});
  /*** Hide navbar when scrolling down ***/
  // Returns true when headerlink target matches hash in url
  (function() {
    hashTargetOnTop = function() {
        var hash = window.location.hash;
        if ( hash.length < 2 ) { return false; }

        var target = document.getElementById( hash.slice(1) );
        if ( target === null ) { return false; }

        var top = target.getBoundingClientRect().top;
        return (top < 2) && (top > -2);
    };

    // Hide navbar on load if hash target is on top
    var navBar = document.getElementById("navbar");
    var navBarToggler = document.getElementById("sk-navbar-toggler");
    var navBarHeightHidden = "-" + navBar.getBoundingClientRect().height + "px";
    var $window = $(window);

    hideNavBar = function() {
        navBar.style.top = navBarHeightHidden;
    };

    showNavBar = function() {
        navBar.style.top = "0";
    }

    if (hashTargetOnTop()) {
        hideNavBar()
    }

    var prevScrollpos = window.pageYOffset;
    hideOnScroll = function(lastScrollTop) {
        if (($window.width() < 768) && (navBarToggler.getAttribute("aria-expanded") === 'true')) {
            return;
        }
        if (lastScrollTop > 2 && (prevScrollpos <= lastScrollTop) || hashTargetOnTop()){
            hideNavBar()
        } else {
            showNavBar()
        }
        prevScrollpos = lastScrollTop;
    };

    /*** high preformance scroll event listener***/
    var raf = window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;
    var lastScrollTop = $window.scrollTop();

    if (raf) {
        loop();
    }

    function loop() {
        var scrollTop = $window.scrollTop();
        if (lastScrollTop === scrollTop) {
            raf(loop);
            return;
        } else {
            lastScrollTop = scrollTop;
            hideOnScroll(lastScrollTop);
            raf(loop);
        }
    }
  })();
});

</script>
    
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js"></script>
    
</body>
</html>